package tmt.usercenter.web.domain.enums;

import com.tmt.annotation.EnumDescriptor;
import com.tmt.annotation.parser.EnumAnnotationParser;
import lombok.Getter;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Getter
public enum RoleItem {

    @EnumDescriptor(title = "TMT超级管理员", description = "TMT用户中心的管理员")
    SUPER_ADMIN(false, AuthorityItem.values()),

    @EnumDescriptor(title = "客户管理员", description = "客户系统的管理员")
    CLIENT_ADMIN(false, getValidAuthorities(new String[]{"ADMIN"}, null)),

    @EnumDescriptor(title = "实名审核员", description = "注册用户实名审核员")
    REAL_NAME_CHECKER(false, getValidAuthorities(new String[]{"REAL_NAME"}, null)),

    @EnumDescriptor(title = "注册用户", description = "客户系统的注册用户")
    REG_USER(true, getValidAuthorities(new String[]{"FRONT"}, null));

    private boolean defaultRole;

    private AuthorityItem[] authorities;

    RoleItem(boolean defaultRole, AuthorityItem[] authorities) {
        this.defaultRole = defaultRole;
        this.authorities = authorities;
    }

    public static AuthorityItem from(String title) {
        return EnumAnnotationParser.convertFromTitle(AuthorityItem.class, title);
    }

    protected static AuthorityItem[] getValidAuthorities(String[] clientTags, AuthorityItem[] additionalAuthorities) {
        List<AuthorityItem> validList = new ArrayList<>();

        AuthorityItem[] all = AuthorityItem.values();

        if (clientTags != null && clientTags.length > 0) {
            List<String> tags = Arrays.asList(clientTags);
            Arrays.asList(all).forEach(x -> {
                if (x.getClientTag() != null && tags.stream().anyMatch(y -> x.getClientTag().contains(y)))
                    validList.add(x);
            });
        }

        if (additionalAuthorities != null)
            validList.addAll(Arrays.asList(additionalAuthorities));

        AuthorityItem[] result = new AuthorityItem[validList.size()];
        return validList.toArray(result);
    }
}
